/**
 * 
 */
package mx.netbrain.bean;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import org.apache.log4j.Logger;
import javax.faces.context.FacesContext;

import mx.netbrain.dao.UserDao;
import mx.netbrain.dao.impl.UserDaoImpl;
import mx.netbrain.model.User;

import org.primefaces.context.RequestContext;

/**
 * @author julian
 * 
 */
public class UserLoginBean {

	private static final Logger logger = Logger.getLogger(UserLoginBean.class);
	private String username;
	private String password;
	private User user;

	public UserLoginBean() {
	}

	public String validateLogin() {
		UserDao userDao = new UserDaoImpl();
		RequestContext context = RequestContext.getCurrentInstance();
		boolean loggedIn = false;
		ExternalContext externalContent = FacesContext.getCurrentInstance()
				.getExternalContext();
		user = userDao.findForUser(username, password);
		if (user != null) {
			loggedIn = true;
			context.addCallbackParam("loggedIn", loggedIn);
			externalContent.getSessionMap().put("userSession", user);
			if (user.getType() == 1) {
				logger.info("Se inicio sesión con usuario: "
						+ user.getUsername());
				return "admin";
			} else {
				logger.info("Se inicio sesión con usuario: "
						+ user.getUsername());
				return "user";
			}
		} else {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error",
					"Error al iniciar sesión");
			FacesContext.getCurrentInstance().addMessage(null, message);
			logger.error("Error al iniciar sesión");
			return "error";
		}
	}

	public boolean isLoggedIn() {
		return username != null;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}
